# -*- coding:utf-8 -*-
# -1- 客户端登录时，提供用户名与密码，POST到服务器上
# -2- 服务器验证用户名与密码，如果失败，则返回错误码，否则
# -3- 用户名与密码验证通过后，返回一个session_string(base64)，客户端保存，同时服务端存储于memcache中
# -4- 客户端每次提交操作都携带这个session_string，服务端从session_string中得到用户信息
# -5- 每次修改密码时，需要在服务端作废session_string
#
# session-format: '%u#%s#%u#%u#%u' % (user_id, user_name, birth_year, sex, gen_time, )
import os, base64, time, hashlib
os.sys.path.append('../user/')
import userLogic

class session(object):
    "session operations"
    def __init__(self):
        self.__session_format = '%u#%s#%u#%u#%u'
    def encode(self, user_item,):
        # -1- 按格式print
        session_format = self.__session_format
        session_string = session_format % (\
                user_item['user_id'], \
                user_item['user_name'], \
                user_item['birth_year'], \
                user_item['sex'], \
                int(time.time()), \
                )
        # -2- 计算md5
        session_md5sum = hashlib.md5(session_string).hexdigest()
        # -3- 计算base64编码
        session_base64 = base64.standard_b64encode("%s:%s" % (session_string, session_md5sum))
        # -4- 存储于memcache中
        # key = "%s:%u" % ('session')
        return session_base64
    def decode(self, session_base64,):
        ret = {}
        ret['status'] = True
        ret['message'] = "OK"
        session_base64 = base64.standard_b64decode(session_base64)
        session_string, session_md5sum = session_base64.split(':')
        if session_md5sum != hashlib.md5(session_string).hexdigest():
            ret['status'] = False
            ret['message'] = 'session_md5sum not match.'
            return ret
        user_info = {}
        user_id, user_name, birth_year, sex, gen_time = session_string.split('#')
        user_info['user_id']    = int(user_id)
        user_info['user_name']  = user_name
        user_info['birth_year'] = int(birth_year)
        user_info['sex']        = int(sex)
        user_info['gen_time']   = int(gen_time)
        ret['user_info'] = user_info
        return ret
